package com.the4man.framework.util;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

import java.io.IOException;
import java.io.StringWriter;
import java.text.DateFormat;

/**
 * Created by lenovo on 2017/12/12.
 */
public class JacksonUtil {
    public JacksonUtil() {
    }

    public static String toJson(Object object) throws IOException {
        ObjectMapper mapper = JacksonMapper.getInstance();
        mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        String json = getJsonStr(mapper, object);
        return json;
    }

    public static String toJson(Object object, DateFormat dateFormat) throws IOException {
        ObjectMapper mapper = JacksonMapper.getInstance();
        mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        if(dateFormat != null) {
            mapper.setDateFormat(dateFormat);
        } else {
            mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        }

        String json = getJsonStr(mapper, object);
        return json;
    }

    public static String getJsonStr(ObjectMapper mapper, Object object) throws IOException {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = (new JsonFactory()).createJsonGenerator(sw);
        mapper.writeValue(gen, object);
        gen.close();
        String json = sw.toString();
        return json;
    }
}
